#include <stdio.h>
#include "hal_debug_uart.h"


UART_HandleTypeDef huart1;
uart_t g_debug_uart;
uint8_t g_debug_rx_char;


static void Error_Handler(void)
{
    /* USER CODE BEGIN Error_Handler_Debug */
    /* User can add his own implementation to report the HAL error return state */
    __disable_irq();
    while (1)
    {
    }
    /* USER CODE END Error_Handler_Debug */
}

void hal_debug_uart_init(void)
{
    huart1.Instance = USART1;
    huart1.Init.BaudRate = 115200;
    huart1.Init.WordLength = UART_WORDLENGTH_8B;
    huart1.Init.StopBits = UART_STOPBITS_1;
    huart1.Init.Parity = UART_PARITY_NONE;
    huart1.Init.Mode = UART_MODE_TX_RX;
    huart1.Init.HwFlowCtl = UART_HWCONTROL_NONE;
    huart1.Init.OverSampling = UART_OVERSAMPLING_16;
    huart1.Init.OneBitSampling = UART_ONE_BIT_SAMPLE_DISABLE;
    huart1.Init.ClockPrescaler = UART_PRESCALER_DIV1;
    huart1.AdvancedInit.AdvFeatureInit = UART_ADVFEATURE_NO_INIT;
    if (HAL_UART_Init(&huart1) != HAL_OK)
    {
        Error_Handler();
    }
    if (HAL_UARTEx_SetTxFifoThreshold(&huart1, UART_TXFIFO_THRESHOLD_1_8) != HAL_OK)
    {
        Error_Handler();
    }
    if (HAL_UARTEx_SetRxFifoThreshold(&huart1, UART_RXFIFO_THRESHOLD_1_8) != HAL_OK)
    {
        Error_Handler();
    }
    if (HAL_UARTEx_DisableFifoMode(&huart1) != HAL_OK)
    {
        Error_Handler();
    }
}


int32_t hal_debug_uart_write(uint8_t *data, uint32_t data_len)
{   
    if (data == NULL)
        return -1;
    
    HAL_UART_Transmit(&huart1, data, data_len, HAL_MAX_DELAY);
    
    return data_len;
}

//int32_t hal_debug_uart_read(uint8_t *buff, uint32_t buff_len)
//{
//    return rx_fifo_out(&g_debug_uart, buff, buff_len);
//}


#if defined(__ARMCC_VERSION) || defined(__ICCARM__)
int fputc(int ch, __attribute__((unused))FILE *f)
#elif __GNUC__
int __io_putchar(int ch)
#endif
{
    hal_debug_uart_write((uint8_t *)&ch, 1);
    return ch;
}


